package edu.boun.g4.coursity.freebase;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import com.jayway.jsonpath.JsonPath;

/**
 * 
 * @author mertusta
 * 
 */
public class FreebaseSemanticTagging {
	public static String API_KEY = "AIzaSyBPIWQ-O9_cQt7px9Vog73ns4V_pMKjOXo";

	public List<FreebaseTag> getTags(String queryString) {

		HttpClient httpclient = new DefaultHttpClient();
		JSONParser parser = new JSONParser();

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("query", queryString));
		params.add(new BasicNameValuePair("key", API_KEY));

		String serviceURL = "https://www.googleapis.com/freebase/v1/search";
		String url = serviceURL + "?" + URLEncodedUtils.format(params, "UTF-8");
		HttpResponse httpResponse;
		JSONObject response = null;

		try {
			httpResponse = httpclient.execute(new HttpGet(url));
			response = (JSONObject) parser.parse(EntityUtils
					.toString(httpResponse.getEntity()));
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (org.json.simple.parser.ParseException e) {
			e.printStackTrace();
		}

		List<FreebaseTag> list = new ArrayList<FreebaseTag>();

		JSONArray results = (JSONArray) response.get("result");

		for (Object result : results) {
			FreebaseTag freebaseTag = new FreebaseTag();
			freebaseTag.setName(JsonPath.read(result, "name").toString());

			if (result.toString().contains("notable")) {
				freebaseTag.setNotableId(JsonPath.read(result, "$.notable.id")
						.toString());
				freebaseTag.setNotableName(JsonPath.read(result,
						"$.notable.name").toString());
			}
			list.add(freebaseTag);
		}
		return list;
	}

}